﻿using FreeRedis;
using LeoGemini.Service.Infrastructure.Json.Resolver;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Volo.Abp.Modularity;

namespace LeoGemini.Service.Common.Module
{
    public class LeoGeminiFreeRedisModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var services = context.Services;
            var configuration = context.Services.GetConfiguration();
            
            services.AddSingleton<RedisClient>(serviceProvider =>
            {
                // 重写redis的json反序列化配置
                var serializerSettings = new JsonSerializerSettings
                {
                    ContractResolver = new PrivateSetterContractResolver(),
                    ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
                };
                
                // 创建redis客户端
                var client = new RedisClient(configuration["Cache:Master"])
                {
                    Serialize = JsonConvert.SerializeObject,
                    Deserialize = (strObj, type) => JsonConvert.DeserializeObject(strObj, type, serializerSettings)
                };

                // 定义序列化方法
                return client;
            });
        }
    }
}